package com.example.spring.security.demo.controller;

import com.example.spring.security.demo.config.validate.image.ImageCode;
import com.example.spring.security.demo.config.validate.ValidateCode;
import com.example.spring.security.demo.config.validate.ValidateCodeGenerator;
import com.example.spring.security.demo.config.validate.sms.sender.SmsCodeSender;
import com.example.spring.security.demo.properties.SecurityConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.ServletWebRequest;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

@RestController
public class ValidateCodeController {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private ValidateCodeGenerator smsCodeGenerator;
    @Autowired
    private ValidateCodeGenerator imageCodeGenerator;
    @Autowired
    private SmsCodeSender smsCodeSender;

    @GetMapping("/code/image")
    public void createImageCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
        ImageCode imageCode = (ImageCode) imageCodeGenerator.generate(new ServletWebRequest(request,response));
        //TODO 写入redis
        stringRedisTemplate.opsForValue().set(SecurityConstants.DEFAULT_PARAMETER_NAME_CODE_IMAGE, imageCode.getCode(), 60, TimeUnit.SECONDS);
        ImageIO.write(imageCode.getImage(),"JPEG",response.getOutputStream());

    }

    @GetMapping("/code/sms")
    public void createSmsCode(HttpServletRequest request, HttpServletResponse response) throws ServletRequestBindingException {

        ValidateCode smsCode = smsCodeGenerator.generate(new ServletWebRequest(request,response));
        //sessionStrategy.setAttribute(new ServletWebRequest(request),)
        stringRedisTemplate.opsForValue().set(SecurityConstants.DEFAULT_PARAMETER_NAME_CODE_SMS, smsCode.getCode(), 600, TimeUnit.SECONDS);
        String mobile = ServletRequestUtils.getRequiredStringParameter(request,"mobile");

        //短信供应商有不同，需要定义一个接口来发送
        smsCodeSender.send(mobile,smsCode.getCode());
    }


}
